package org.dromara.xxmj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.xxmj.domain.CourseExercise;
import org.dromara.xxmj.domain.UserExerciseRecord;
import org.dromara.xxmj.domain.dto.ExerciseSubmitDto;
import org.dromara.xxmj.domain.po.UserCollectQuestionInfo;
import org.dromara.xxmj.domain.vo.*;
import org.dromara.xxmj.mapper.*;
import org.dromara.xxmj.domain.po.UserErrorQuestionInfo;
import org.dromara.xxmj.service.ICourseExerciseService;
import org.dromara.xxmj.utils.CheckUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 课程习题服务实现类
 *
 * @author Vincent
 */
@RequiredArgsConstructor
@Service
public class CourseExerciseServiceImpl implements ICourseExerciseService {

    @Resource
    private CourseExerciseMapper courseExerciseMapper;

    @Resource
    private CourseQuestionMapper courseQuestionMapper; //刷题题库

    @Resource
    private CourseSimulationMapper courseSimulationMapper;//模拟题库

    @Resource
    private UserErrorQuestionInfoMapper  userErrorQuestionInfoMapper;

    @Resource
    private UserCollectQuestionInfoMapper  userCollectQuestionInfoMapper;

    @Resource
    private UserExerciseRecordMapper recordMapper;

    @Resource
    private CheckUtils checkUtils;

    /**
     * 获取视频关联的习题列表
     *
     * @param videoId 视频ID
     * @return 习题列表
     */
    @Override
    public List<CourseExerciseVo> listExercisesByVideo(Long courseId,Long videoId) {
        Long userId = LoginHelper.getUserId();
        List<CourseExerciseVo> exerciseList = courseExerciseMapper.selectExercisesByVideoId(courseId,videoId, userId);

        // 处理选项
        for (CourseExerciseVo vo : exerciseList) {
            processOptions(vo);
        }

        return exerciseList;
    }

    /**
     * 获取习题详情
     *
     * @param id 习题ID
     * @return 习题详情
     */
    @Override
    public CourseExerciseVo getExerciseDetail(Long id) {
        Long userId = LoginHelper.getUserId();
        CourseExerciseVo vo = courseExerciseMapper.selectExerciseDetail(id,  userId);
        if (vo != null) {
            processOptions(vo);
        }
        return vo;
    }

    /**
     * 提交习题答案
     *
     * @param dto 提交信息
     * @return 是否正确
     */
    @Override
    public Boolean submitAnswer(ExerciseSubmitDto dto) {
        Long userId = LoginHelper.getUserId();
        Long exerciseId = dto.getExerciseId();
        Integer courseType = dto.getCourseType();

        CourseGeneralVO generalVO = new CourseGeneralVO();
        switch (courseType) {
            case 1 -> {
                // 获取习题
                CourseExercise exercise = courseExerciseMapper.selectById(exerciseId);
                BeanUtil.copyProperties(exercise, generalVO,"id");
            }
            case 2 -> {
                CourseQuestionVO question = courseQuestionMapper.selectVoById(exerciseId);
                BeanUtil.copyProperties(question, generalVO,"id");
            }
            case 4 -> {
                UserErrorQuestionInfo errorQustion = userErrorQuestionInfoMapper.selectOne(Wrappers.<UserErrorQuestionInfo>lambdaQuery().eq(UserErrorQuestionInfo::getStuId, userId)
                    .eq(UserErrorQuestionInfo::getQuestionId, exerciseId));
                BeanUtil.copyProperties(errorQustion, generalVO, "id");
            }
            case 5 -> {
                UserCollectQuestionInfo collectQustion = userCollectQuestionInfoMapper.selectOne(Wrappers.<UserCollectQuestionInfo>lambdaQuery().eq(UserCollectQuestionInfo::getStuId, userId)
                    .eq(UserCollectQuestionInfo::getQuestionId, exerciseId));
                BeanUtil.copyProperties(collectQustion, generalVO,"id");
            }
            default -> throw new ServiceException("未知的题目类型");
        }

        // 判断答案是否正确
        boolean isCorrect = checkUtils.checkAnswer(generalVO, dto.getUserAnswer());
        dto.setIsCorrect(isCorrect ? "1" : "0");

        // 保存用户答题记录
        LambdaQueryWrapper<UserExerciseRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserExerciseRecord::getUserId, userId).eq(UserExerciseRecord::getQuestionType, courseType)
            .eq(UserExerciseRecord::getExerciseId, exerciseId);

        //当类型为习题,及刷题时，更新记录
        if (generalVO.getCourseId() == null){
            throw new ServiceException("暂无此课程");
        }
        UserExerciseRecord record = recordMapper.selectOne(queryWrapper);
        if (record != null) {
            // 更新记录
            record.setUserAnswer(dto.getUserAnswer());
            record.setCourseId(generalVO.getCourseId());
            record.setQuestionType(courseType);
            record.setIsCorrect(dto.getIsCorrect());
            recordMapper.updateById(record);
        } else {
            // 新增记录
            record = new UserExerciseRecord();
            record.setUserId(userId);
            record.setExerciseId(exerciseId);
            record.setCourseId(generalVO.getCourseId());//课程ID
            if  (courseType == 1) {
                record.setVideoId(generalVO.getVideoId());
            }
            record.setUserAnswer(dto.getUserAnswer());
            record.setQuestionType(courseType); //类型
            record.setIsCorrect(dto.getIsCorrect());
            record.setUpdateTime(new Date());
            record.setCreateTime(new Date());
            recordMapper.insert(record);
        }

        // 查询是否已存在该错题记录
        LambdaQueryWrapper<UserErrorQuestionInfo> errorQuestionWrapper = Wrappers.<UserErrorQuestionInfo>lambdaQuery()
            .eq(UserErrorQuestionInfo::getStuId, userId).eq(UserErrorQuestionInfo::getQuestionId, exerciseId)
            .eq(UserErrorQuestionInfo::getCourseId, generalVO.getCourseId());

        UserErrorQuestionInfo existingRecord = userErrorQuestionInfoMapper.selectOne(errorQuestionWrapper);

        //错题库
        if (dto.getIsCorrect().equals("0")) {
            //如果没有此错题，则加入错题本
            if (existingRecord == null) {
                UserErrorQuestionInfo userErrorQuestionInfo = new UserErrorQuestionInfo();
                BeanUtil.copyProperties(generalVO, userErrorQuestionInfo,"id");

                userErrorQuestionInfo.setStuId(Convert.toStr(userId)); //学生ID
                userErrorQuestionInfo.setQuestionId(exerciseId); //习题ID
                userErrorQuestionInfo.setType(generalVO.getType());
                userErrorQuestionInfo.setQuestionType(courseType);
                userErrorQuestionInfo.setSaveTime(new Date());

                try {
                    userErrorQuestionInfoMapper.insert(userErrorQuestionInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ServiceException("新增用户错题库 userErrorQuestionInfoMapper.insert .Error");
                }
            }
        } else if (dto.getIsCorrect().equals("1") && existingRecord != null) {
            try {
                userErrorQuestionInfoMapper.delete(errorQuestionWrapper);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("删除用户错题库 userErrorQuestionInfoMapper.delete .Error");
            }
        }

        return isCorrect;
    }

    /**
     * 获取用户习题完成率
     *
     * @param videoId 视频ID
     * @return 完成率
     */
    @Override
    public Integer getUserExerciseCompletedRate(Long videoId) {
        Long userId = LoginHelper.getUserId();

        // 获取视频关联的习题总数
        LambdaQueryWrapper<CourseExercise> exerciseWrapper = Wrappers.lambdaQuery();
        exerciseWrapper.eq(CourseExercise::getVideoId, videoId);
        long totalCount = courseExerciseMapper.selectCount(exerciseWrapper);

        if (totalCount == 0) {
            return 100; // 没有习题，认为已全部完成
        }

        // 获取用户完成的习题数
        Integer completedCount = recordMapper.getUserExerciseCompletedCount(userId, videoId);
        if (completedCount == null) {
            return 0;
        }

        // 计算完成率
        return (int) (completedCount * 100 / totalCount);
    }

    /**
     * 处理习题选项
     */
    private void processOptions(CourseExerciseVo vo) {
        if (StringUtils.isNotEmpty(vo.getOptions())) {
            try {
                vo.setOptionList(JsonUtils.parseArray(vo.getOptions(), Map.class));
            } catch (Exception e) {
                vo.setOptionList(null);
            }
        }
    }

}
